//
//  SheetGestureController.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 02.04.25.
//

import SwiftUI
import UIKit

class SheetGestureController: UIViewController {
    var onDragChanged: ((CGFloat) -> Void)?
    var onDragEnded: ((CGFloat) -> Void)?
    
    private var initialTouchPoint: CGPoint = .zero
    private var isVerticalPan: Bool = false
    private let verticalThreshold: CGFloat = 10 // 垂直移动阈值
    private let horizontalThreshold: CGFloat = 8 // 水平移动阈值
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        panGesture.delegate = self
        view.addGestureRecognizer(panGesture)
        view.backgroundColor = .clear
    }
    
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        
        switch gesture.state {
        case .began:
            initialTouchPoint = gesture.location(in: view)
            isVerticalPan = false
            
        case .changed:
            // 在手势开始时判断移动方向
            if !isVerticalPan && abs(translation.y) < verticalThreshold {
                // 如果还没确定是垂直滑动，且垂直移动距离小于阈值，暂不处理
                return
            }
            
            // 第一次超过阈值时，判断是否为垂直滑动
            if !isVerticalPan {
                let horizontal = abs(translation.x)
                let vertical = abs(translation.y)
                isVerticalPan = vertical > horizontal && vertical > verticalThreshold
                
                // 如果不是垂直滑动，取消该手势
                if !isVerticalPan {
                    gesture.state = .cancelled
                    return
                }
            }
            
            // 确认为垂直滑动后，传递移动距离
            if isVerticalPan {
                onDragChanged?(translation.y)
            }
            
        case .ended, .cancelled:
            if isVerticalPan {
                let velocity = gesture.velocity(in: view)
                onDragEnded?(velocity.y)
            }
            isVerticalPan = false
            
        default:
            break
        }
    }
}

extension SheetGestureController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                          shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 如果已确定是垂直滑动，则不允许其他手势
        if let panGesture = gestureRecognizer as? UIPanGestureRecognizer,
           isVerticalPan {
            return false
        }
        return true
    }
    
    // 允许手势开始，后续在 handlePan 中进行更细致的判断
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                          shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 让其他手势等待我们的手势失败
        return false
    }
}
// UIViewController 表示层
struct SheetGestureRepresentable: UIViewControllerRepresentable {
    var onDragChanged: (CGFloat) -> Void
    var onDragEnded: (CGFloat) -> Void
    
    func makeUIViewController(context: Context) -> SheetGestureController {
        let controller = SheetGestureController()
        controller.onDragChanged = onDragChanged
        controller.onDragEnded = onDragEnded
        return controller
    }
    
    func updateUIViewController(_ uiViewController: SheetGestureController, context: Context) {
        uiViewController.onDragChanged = onDragChanged
        uiViewController.onDragEnded = onDragEnded
    }
}
